//
//  OrderdetailVC.m
//  phmall
//
//  Created by admin on 2017/12/15.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "OrderdetailVC.h"
#import "OrderCell.h"
#import "OrderStatusView.h"
#import "CommodityDetailsVC.h"
#import "OrderInformationView.h"
#import "PaymentView.h"
#import "Ipay88PayVC.h"
@interface OrderdetailVC ()<UITableViewDelegate,UITableViewDataSource,PaymentViewDelegate>{
    UIView *headerView;
    OrderInformationView *information;
    OrderStatusView *order;
    UIView *footerView;
    UIImageView *background;
    PaymentView *pay;
}
@property(strong,nonatomic)UITableView *myTableview;
@property(strong,nonatomic)OrderModel *model;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation OrderdetailVC
- (void)loadDataWithorder:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_order"];
    
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:self.ordersn forKey:@"ordersn"];
    [parametersDic setValue:@"0" forKey:@"start"];
    [parametersDic setValue:@"0" forKey:@"status"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
                NSMutableDictionary *dict=data[0];
                self.model = [OrderModel yy_modelWithDictionary:dict];
                //添加webview前计算一次高度
                order.model=self.model;
                information.model=self.model;
                
                CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
                CGRect frame = headerView.bounds;
                frame.size.height = height;
                headerView.frame = frame;
                [self.myTableview setTableHeaderView:headerView];
                [headerView layoutIfNeeded];
                //添加webview前计算一次高度
                CGFloat height2 = [footerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
                CGRect frame2 = footerView.bounds;
                frame2.size.height = height2;
                footerView.frame = frame2;
                [self.myTableview setTableFooterView:footerView];
                [footerView layoutIfNeeded];
                
                [self addFooterView];
                [self.myTableview reloadData];
            }
        }
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.emptyType=EmptyDataSetNoNetwork;

    }];
    
}
-(void)butAction:(UIButton *)sender{
 
    if ([sender.titleLabel.text isEqualToString:Localized(@"付款")]) {
//        payOrder=self.model;
        [self PaymentView];
    }
    if ([sender.titleLabel.text isEqualToString:Localized(@"取消")]) {
        [self tapAvatarView:self.model.uid];
    }
}
-(void)Passwordill:(NSString *)password{
    [self close];

    self.hud =[MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"pay"];
    
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:@"0" forKey:@"advance"];
    [parametersDic setValue:password forKey:@"pay_pass"];
    [parametersDic setValue:@"16" forKey:@"pay_id"];
    [parametersDic setValue:self.model.ordersn forKey:@"orderid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] doubleValue] == 200) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                if ([responseDict[@"status"] isEqualToString:@"1"]) {
                    [PublicClass ProgressHUDModeText:@"支付成功" andTime:2];
                }else{
                    [PublicClass ProgressHUDModeText:@"支付失败" andTime:2];
                }
                
                self.hidesBottomBarWhenPushed=YES;
                OrderdetailVC *evaluate=[[OrderdetailVC alloc]init];
                evaluate.ordersn=self.model.ordersn;
                [self.navigationController pushViewController:evaluate animated:YES];
                
            }
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];

}

-(void)tapAvatarView:(NSString *)uid{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"我不想买了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadDataWithOrderDetele:uid];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"信息填错,重新拍" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadDataWithOrderDetele:uid];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"卖家迟迟不发货" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadDataWithOrderDetele:uid];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"误点错拍" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadDataWithOrderDetele:uid];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"其他原因" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self loadDataWithOrderDetele:uid];
    }]];
    
    [self.navigationController presentViewController:alertController animated:YES completion:nil];
    
}
-(void)loadDataWithOrderDetele:(NSString *)uid{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_order/cancel"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:uid forKey:@"uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
        
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                if ([responseDict[@"status"] isEqualToString:@"1"]) {
                    [PublicClass ProgressHUDModeText:@"订单已取消" andTime:2 ];
                    [self loadDataWithorder:YES];
                }
            }
        }else{
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
        }
        
    } andFailure:^{
        
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}

-(void)PaymentView{
    if ([self.model.pay_id isEqualToString:@"16"]) {
        Ipay88PayVC *ipay=[[Ipay88PayVC alloc]init];
        ipay.payOrder=self.model;
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:ipay animated:YES];
        
    }else{
        background=[UIImageView new];
        background.image=[UIImage imageNamed:@"透明图片"];
        [[UIApplication sharedApplication].keyWindow addSubview:background];
        [background mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.offset(0);
        }];
        //    background.hidden=YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
        background.userInteractionEnabled=YES;
        [background addGestureRecognizer:tap];
        
        pay=[[PaymentView alloc]init];
        pay.delegate=self;
        ViewBorderRadius(pay, 10, 0, [UIColor clearColor]);
        [[UIApplication sharedApplication].keyWindow addSubview:pay];
        [pay mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.centerY.offset(-60);
            make.width.offset(280);
            make.height.offset(260);
        }];
    }
}
-(void)close{
    background.hidden=YES;
    pay.hidden=YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=Localized(@"订单详情");
    [self loadDataWithorder:YES];
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(self.tabBar_height-44);
    }];

    //整体界面
    headerView=[UIView new];
    headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];

    order=[[OrderStatusView alloc]init];
    [headerView addSubview:order];
    
    [order mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(order.addressView.mas_bottom).offset(1);
        make.bottom.equalTo(headerView.mas_bottom).offset(-10).priorityHigh();
    }];
    [order layoutIfNeeded];
    
    footerView=[UIView new];
    footerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //轮播图
    
    information=[[OrderInformationView alloc]init];
    [footerView addSubview:information];
    [information mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(information.codeView.mas_bottom).offset(1);
        make.bottom.equalTo(footerView.mas_bottom).offset(-10).priorityHigh();
    }];
    [information layoutIfNeeded];
    

    // Do any additional setup after loading the view.
}
-(void)addFooterView{
    //底部背景
    UIView *footerView=[UIView new];
    footerView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:footerView];
    [footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-self.tabBar_height);
        make.left.right.offset(0);
        make.height.offset(44);
    }];
    
    NSMutableArray *butArr = [NSMutableArray array];
    NSArray *titleArr=[NSArray array];
        switch ([self.model.status_num intValue]) {
            case 1:
                titleArr=@[Localized(@"取消"),Localized(@"付款")];
                break;
            case 2:
                titleArr=@[Localized(@"查看物流"),Localized(@"确认收货")];
                break;
            case 3:
                titleArr=@[Localized(@"申请退款")];
                break;
            case 4:
                titleArr=@[Localized(@"查看物流"),Localized(@"确认收货")];
                break;
            case 5:
                titleArr=@[Localized(@"申请售后"),Localized(@"评价")];
                break;
    
            default:
                break;
        }
    for (int i=0; i<titleArr.count; i++) {
        UIButton *but=[UIButton buttonWithType:UIButtonTypeCustom];
        [footerView addSubview:but ];
        [but setTitle:titleArr[i] forState:UIControlStateNormal];
        if (i==titleArr.count-1) {
            ViewBorderRadius(but, 6, 1, [UIColor colorWithHexString:@"feba03"]);
            [but setTitleColor:[UIColor colorWithHexString:@"feba03"] forState:UIControlStateNormal];
        }else{
            ViewBorderRadius(but, 6, 1, [UIColor blackColor]);
            [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        but.titleLabel.font=[UIFont systemFontOfSize:13];
        [but addTarget:self action:@selector(butAction:) forControlEvents:UIControlEventTouchUpInside];
        
        if (titleArr.count<=1) {
            [but mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(footerView).offset(0);
                make.height.mas_equalTo(30);
                make.right.offset(-10);
                make.width.offset(80);
            }];
        }else{
            [butArr addObject:but];
        }
        
    }
    
    if (butArr.count>1) {
        [butArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:80 leadSpacing:SCREEN_WIDTH-titleArr.count*90 tailSpacing:10];
        [butArr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(footerView).offset(0);
            //        UIView *blueView = (UIView *)blueViews[0];
            make.height.mas_equalTo(30);
        }];
    }
    
    
    UIView *line=[[UIView alloc]init];
    [footerView addSubview:line];
    line.backgroundColor=[UIColor colorWithHexString:@"#ECEBEC"];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(0.5);
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSMutableArray *data=self.model.goods_list;
    return data.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.model==nil) {
        return 0;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *nameView=[[UIView alloc]init];
    nameView.backgroundColor=[UIColor whiteColor];
    
    UILabel *name=[UILabel new];
    name.text=self.model.shop_name;
    name.numberOfLines=2;
    name.font=[UIFont systemFontOfSize:15];
    [nameView addSubview:name];
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameView);
        make.left.offset(10);
    }];
    
    UILabel *line=[UILabel new];
    line.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [nameView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nameView.mas_bottom).offset(0);
        make.left.equalTo(nameView).with.offset(0);
        make.right.equalTo(nameView).with.offset(0);
        make.height.mas_equalTo(1);
    }];
    
    return nameView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]init];
    footerView.backgroundColor=[UIColor whiteColor];
    
   
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderCell *cell=[OrderCell theShareCellWithTableView:tableView];
    NSMutableArray *data=self.model.goods_list;
    GoodsListModel *goodsModel=data[indexPath.row];
    cell.model=goodsModel;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsListModel *model=self.model.goods_list[indexPath.row];
    self.hidesBottomBarWhenPushed=YES;
    CommodityDetailsVC *deta=[[CommodityDetailsVC alloc] init];
    deta.uid=model.g_uid;
    [self.navigationController pushViewController:deta animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
    }
    return _myTableview;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
